<template>
	<el-form ref="form" :size="size" :model="formData" :rules="formRules" label-position="top" class="sw_agent_form">
		<el-form-item v-for="(item, index) in formItems" :key="index" :label="item.label" :prop="item.variable">
			<template v-if="item.type === 'select'">
				<el-select v-model="formData[item.variable]" :placeholder="item.label" :disabled="disabled" style="width: 100%">
					<el-option v-for="(n, i) in item.options" :key="i" :label="n" :value="n"></el-option>
				</el-select>
			</template>
			<template v-if="item.type === 'paragraph'">
				<el-input v-model="formData[item.variable]" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" :placeholder="item.label" />
			</template>
			<template v-if="item.type === 'text-input'">
				<el-input v-model="formData[item.variable]" :placeholder="item.label"></el-input>
			</template>
		</el-form-item>
		<el-form-item v-if="$slots.default">
			<slot></slot>
		</el-form-item>
	</el-form>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
export default {
	props: {
		value: { type: Object, default: () => ({}) },
		disabled: { type: Boolean, default: false },
		size: { type: String, default: '' }
	},
	data() {
		return {
			formData: this.value
		};
	},
	computed: {
		...mapGetters(['userInputForm']),
		formItems() {
			return this.userInputForm.map((item) => {
				return Object.values(item)[0];
			});
		},
		formRules() {
			let keyData = lodash.keyBy(this.formItems, 'variable');
			return lodash.mapValues(keyData, (n) => {
				if (['paragraph', 'text-input'].includes(n.type)) {
					return [{ required: n.required, message: `请输入${n.label}`, trigger: 'blur' }];
				} else {
					return [{ required: n.required, message: `请选择${n.label}`, trigger: 'change' }];
				}
			});
		}
	},
	watch: {
		value(data) {
			this.formData = data;
		},
		formData(data) {
			this.$emit('input', data);
		}
	},
	methods: {
		validateSetting(callback) {
			this.$refs['form'].validate((valid) => {
				callback.call(this, valid);
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.sw_agent_form {
	padding: 24px 24px 2px;
	&:deep(.el-form-item__label) {
		line-height: 1;
		font-size: 15px;
		font-weight: bold;
	}
	&:deep(.el-button) {
		width: 100%;
	}
}
</style>
